package com.copa.l107;

import java.util.*;

/**
 * @author copa
 * @createDate 2022-05-19 11:37
 * @function DFS
 */
public class Test1 {

    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if (Objects.isNull(root)) {
            return result;
        }
        dfs(root, result, -1);
        // 投机取巧，使用反转集合方法
        Collections.reverse(result);
        return result;
    }

    private void dfs(TreeNode treeNode, List<List<Integer>> result, int startIndex) {
        startIndex++;
        if (treeNode == null) {
            return;
        }
        if (startIndex == result.size()) {
            result.add(new ArrayList<>());
        }
        result.get(startIndex).add(treeNode.val);
        if (Objects.nonNull(treeNode.left)) {
            dfs(treeNode.left, result, startIndex);
        }
        if (Objects.nonNull(treeNode.right)) {
            dfs(treeNode.right, result, startIndex);
        }
    }

    public static void main(String[] args) {
        TreeNode left = new TreeNode(9);
        TreeNode right = new TreeNode(20);
        right.left = new TreeNode(15);
        right.right = new TreeNode(7);
        TreeNode root = new TreeNode(3, left, right);
        List<List<Integer>> result = new Test1().levelOrderBottom(root);
        for (List<Integer> list : result) {
            System.out.println(Arrays.toString(list.toArray()));
        }
    }
}
